import { defineStore } from 'pinia';
import { ref } from 'vue';

const useLocalStore = defineStore(
	'local',
	() => {
		
		const userSelectedIdsMap=ref({
			"categoryId": '',
			"categoryCode": "",
			"examId": "",
			"examCode": "",
			"industryId": "",
			"industryCode": "",
			"categoryName": "",
			"examName": "",
			"industryName": "",
			"sold": false,
			"def": true
		})
		const examResult=ref(null)
		// 至少具有paperId，startTime，recordsId
		const examTimeObj=ref([])
		const randomQuestion=ref(null)
		function setRandomQuestion(obj){
			randomQuestion.value=obj
		}

		
		function setKey(key,value){
			userSelectedIdsMap.value[key]=value
		}
		function setExamResult(obj){
			examResult.value=obj
		}
		function addExamTime(obj){
			// 如果不存在，则加入
			if(!examTimeObj.value.find((e) => {
				return e.paperId === obj.paperId&&e.recordsId==obj.recordsId;
			})){
				examTimeObj.value.push(obj);
			}
		}
		function getExamTime(obj){
			return examTimeObj.value.find(e=>{
				return e.paperId === obj.paperId&&e.recordsId==obj.recordsId;
			})
		}
		function setExamTimeObj(obj){
			examTimeObj.value=obj
		}
		// 万一一个paper有多个recordsId则删除多个
		function clearOneExamTime(obj){
			for(let i in examTimeObj.value){
				if(examTimeObj.value[i].paperId === obj.paperId){
					examTimeObj.value.splice(i,1)
					i--;
				}
			}
		}
		function clear(){
			userSelectedIdsMap.value={
				industryCode :'',
				examId :'',
				categoryId:'',
				industryName :'',
				examName :'',
				categoryName:'',
				collectionType:''
			}
		}
		
		
		return {
			randomQuestion,
			examTimeObj,
			examResult,
			setKey,
			setExamResult,
			clear,
			setExamTimeObj,
			addExamTime,
			getExamTime,
			clearOneExamTime,
			setRandomQuestion
		};
	},
	{
		persist: {
			enabled: true,
			storage: localStorage,
			key: 'local'
		}
	}
);

export default useLocalStore;
